<template>
	<div class="functionChart">
		<el-container class="main" style="height: 88vh">
			<el-main style="width: 25%; background: var(--el-color-white); color: var(--el-text-color-primary)">
				<div class="content">
					<TreeItem v-if="load" ref="Tree" :tree-attr="treeAttr" :events="events" />
				</div>
			</el-main>
			<div style="height: 100%; border-right: 2px sokid #f8f8f8; width: 2px"></div>
			<el-main style="width: 74%; background: var(--el-color-white); color: var(--el-text-color-primary)">
				<div>
					<ViewNode
						:useIcon="UseIcon"
						v-if="status == 'view'"
						:in-node="curNode"
						:item-type-define="itemTypeDefine"
						update-func-name="this.OpDataInfo.updateFuncName"
						:root-node="rootNode"
					/>
				</div>
				<div v-if="status == 'edit'">
					<EditNode
						:useIcon="UseIcon"
						:parent-node="parentNode"
						:in-node="curNode"
						:item-type-define="itemTypeDefine"
						:extDefines="extDefines"
						:events="events"
						:groupID="groupID"
						:root-node="rootNode"
					/>
				</div>

				<div v-if="childTabTitle">
					<h3 style="border-left: 3px solid blue; padding-left: 5px; margin: 20px 0">下级节点列表</h3>
					<el-table :data="childTabView" border style="width: 100%">
						<el-table-column
							v-for="(item, index) in childTabTitle"
							:key="index"
							:prop="item.field"
							:label="item.title"
							align="center"
							:width="item.width"
						/>
					</el-table>
				</div>
			</el-main>
			<!-- 节点删除弹窗 -->
			<el-dialog v-model="isDelDialog" title="删除节点确认" class="NodeDelete">
				<div v-if="curNode">
					<el-row>
						<div>节点名称：{{ curNode.Title }}</div>
					</el-row>
					<el-row style="margin-top: 10px">
						<div>节点编码：{{ curNode.ItemCode }}</div>
					</el-row>
					<div slot="footer" class="dialog-footer">
						<el-button @click="isDelDialog = false">取 消</el-button>
						<el-button type="primary" @click="submitDelNode()">确 定</el-button>
					</div>
				</div>
			</el-dialog>
		</el-container>
	</div>
</template>
<script lang="js">
import TreeItem from '../Tree/TreeItem.vue'
import ViewNode from './viewNode.vue'
import EditNode from './editNode.vue'
// import { Post } from '/@/api/linxyun/base/index.ts'
import { getLocalStorage, getVuex, getObjAttr } from '/@/utils/formatPrivacyData.js'
//import { QuerySubsys } from '@/api/tree'
//import { deleteAuthFunc, deleteFuncUrl } from '@/api/role'
//import { queryFuncUrl, queryFuncTree } from '@/api/linxyun/tree'
import { formatTime2View, formatTime2DB, formatDate2View, formatDate2DB } from '/@/utils/formatTime.js';
import { httpReqeustApi } from '/@/api/linxyun/base';

const httpReqeust = httpReqeustApi();

export default {
	components: { TreeItem, ViewNode, EditNode },
	props: {
		title: { type: String, default: '' },
		treeType: { type: String, default: 'Tree' },
		treeAttr: {
			type: Object,
			default: () => {
				return { treeKey: -1, isEdit: false, isCheckBox: true }
			}
		}
	},
	data() {
		return {
			status: 'view', // view(onSelected), edit(onUpdateNode, onAddNode), del(onDelNode)
			curNode: null,
			childTabTitle: null,
			childTabView: null,
			itemTypeDefine: null,
			extDefines: [],
			isDelDialog: false,
			UseIcon: false,
			groupIDConfig: {},
			groupID: '',
			load: false,
			query: {},
			OpDataInfo: {
				queryFuncName: 'queryTreeData',
				updateFuncName: 'updateTreeData',
				insertFuncName: 'insertTreeData',
				getMaxItemCode: 'treeDataMaxSubItemCode',
				queryRecordsName: 'queryTreeRecords'
			},
			events: {
				loadTree: this.queryTreeData,
				onSelected: this.onSelected,
				onUpdateNode: this.onUpdateNode,
				onAddNode: this.onAddNode,
				onDelNode: this.onDelNode,
				onChecked: null,
				reloadTree: this.reloadTree,
				refreshTree: this.refreshTree
			},
			rootNode:{}
		}
	},
	async created() {
		this.query = this.$route.query
		this.queryParentData()
		this.refreshTree()
	},
	mounted() {},
	methods: {
		async queryParentData() {
			const res = await httpReqeust.Post('queryTreeTopNode', { Level: 0, TreeType: this.treeType })
			console.log('ParentData', res)
			if (res && res.success && res.Records && res.Records.length) {
				this.load = true
				this.parentData = res.Records[0]
				const Data = JSON.parse(this.parentData.Data.replace(/\\/g, ''))
				console.log('DataData', Data)
				this.secdLv = Data.ItemType || ''
				this.Extend = Data.Extend || ''
				// 定义接口的Key:'OpData'
				this.initOpDataInfo(Data.OpData || '')
				this.parentData.OpDataInfo = this.OpDataInfo
				this.Hierarchy = Data.Hierarchy || ''
				this.groupIDConfig = Data.getGroupID || {}
				if (typeof this.Hierarchy === 'undefined') {
					this.Hierarchy = 0
				}
				console.log('this.parentData', this.parentData, this.Extend)
			}
		},
		initOpDataInfo(OpData) {
			let opData = {
				queryFuncName: 'queryTreeData',
				updateFuncName: 'updateTreeData',
				insertFuncName: 'insertTreeData',
				getMaxItemCode: 'treeDataMaxSubItemCode',
				queryRecordsName: 'queryTreeRecords'
			}
			if (OpData !== '') {
				if (OpData.queryFuncName && OpData.queryFuncName.length > 0) {
					opData.queryFuncName = OpData.queryFuncName
				}
				if (OpData.updateFuncName && OpData.updateFuncName.length > 0) {
					opData.updateFuncName = OpData.updateFuncName
				}
				if (OpData.insertFuncName && OpData.insertFuncName.length > 0) {
					opData.insertFuncName = OpData.insertFuncName
				}
				if (OpData.getMaxItemCode && OpData.getMaxItemCode.length > 0) {
					opData.getMaxItemCode = OpData.getMaxItemCode
				}
				if (OpData.queryRecordsName && OpData.queryRecordsName.length > 0) {
					opData.queryRecordsName = OpData.queryRecordsName
				}
			}
			this.OpDataInfo = opData
		},
		async queryTreeData() {
			const params = {
				TreeType: this.treeType,
				Level: 1
			}
			if (this.groupIDConfig && JSON.stringify(this.groupIDConfig) !== '{}') {
				switch (this.groupIDConfig.getFn) {
					case '1':
						this.groupID = params.GroupID = getLocalStorage(this.groupIDConfig.value)
						break
					case '2':
						this.groupID = params.GroupID = getVuex(this.groupIDConfig.value)
						break
					case '3':
						this.groupID = params.GroupID = getObjAttr(this.query, this.groupIDConfig.value)
						break
					case '4':
						this.groupID = params.GroupID = this.groupIDConfig.value
						break
					default:
						break
				}
			}
			let res = await httpReqeust.SyncPost(this.OpDataInfo.queryFuncName, params)
			if (!res || !res.data || !res.code || res.code !== '0000') {
				this.$message({ type: 'error', message: '加载数据字典失败' })
				return null
			}
			console.log('[Debug][DictTree]load: ', res.data)
			const dataTree = res.data

			this.itemTypeDefine = null
			this.extDefines = []
			let tmp = null
			if (dataTree.Data && dataTree.Data !== '') {
				tmp = JSON.parse(dataTree.Data.replace(/\\/g, ''))
				this.UseIcon = tmp?.UseIcon || false
			}
			if (tmp && tmp.ItemType && tmp.ItemType.InputType) {
				if (tmp.ItemType.InputType === '0' && tmp.ItemType.Name) {
					this.itemTypeDefine = tmp.ItemType
				} else if (tmp.ItemType.InputType === '1' && tmp.ItemType.Name && tmp.ItemType.Options) {
					this.itemTypeDefine = tmp.ItemType
				} else {
					console.error('[Error][DictTree]ItemType define invalid: ', tmp.ItemType)
				}
			}
			if (tmp && tmp.Extend) {
				for (let i = 0; i < tmp.Extend.length; i++) {
					if (tmp.Extend[i].key && tmp.Extend[i].title) {
						this.extDefines.push(tmp.Extend[i])
					} else {
						console.error('[Error][DictTree]extend define invalid: ', tmp.Extend[i])
					}
				}
			}

			this.preHandleNode(dataTree)
			this.rootNode = dataTree
			return dataTree
		},
		preHandleNode(node) {
			if (!node) {
				return
			}
			node.Code = node.ItemCode
			node.ParentCode = node.SItemCode
			node.TreeType = this.treeType
			if (this.treeAttr.isEdit) {
				node.canAddChild = true
				node.canUpdate = true
				node.canDelete = true
				if (node.Level === '0') {
					node.canUpdate = false
					node.canDelete = false
				}
			} else {
				node.canAddChild = false
				node.canUpdate = false
				node.canDelete = false
			}

			let etxData = null
			if (node.Data && node.Data !== '') {
				etxData = JSON.parse(node.Data.replace(/\\/g, ''))
			}
			if (this.extDefines.length > 0 && etxData) {
				node.extends = []
				for (let i = 0; i < this.extDefines.length; i++) {
					const fieldName = this.extDefines[i].key
					const title = this.extDefines[i].title
					let value = etxData[fieldName]
					if (value === undefined) {
						value = ''
					}
					node.extends.push({ fieldName: fieldName, title: title, value: value })
				}
			}

			if (!node.Child) {
				return
			}
			for (let i = 0; i < node.Child.length; i++) {
				this.preHandleNode(node.Child[i])
			}
		},
		refreshTree() {
			// ToDo 重新加载树
			console.log('[Debug]reflesh tree: ', this.$refs)
			console.log('[Debug]reflesh tree, cur node: ', this.curNode)

			//this.$refs.Tree.refreshTree(null)
		},
		async reloadTree(reloadNodeCode) {
			// ToDo 重新加载树
			console.log('[Debug][LxyTree]Reload tree, node: ', reloadNodeCode)
			await this.$refs.Tree.reloadTree(reloadNodeCode)
		},
		genChildTabView() {
			this.childTabTitle = null
			this.childTabView = null
			if (!this.curNode || !this.curNode.Child || this.curNode.Child.length === 0) {
				return
			}

			this.childTabTitle = []
			this.childTabTitle.push({ field: 'ItemCode', title: '子级编码', width: 'auto' })
			this.childTabTitle.push({ field: 'Title', title: '名称', width: 'auto' })
			this.childTabTitle.push({ field: 'Level', title: '层级', width: 70 })
			this.childTabTitle.push({ field: 'CTime', title: '创建时间', width: 170 })
			this.childTabTitle.push({ field: 'Status', title: '是否发布', width: 90 })
			let fixedSize = this.childTabTitle.length
			let beginExtIndex = fixedSize
			if (this.itemTypeDefine) {
				this.childTabTitle.push({ field: 'ItemType', title: this.itemTypeDefine.Name, width: 'auto' })
				beginExtIndex++
			}
			for (let i = 0; i < this.extDefines.length; i++) {
				this.childTabTitle.push({ field: this.extDefines[i].key, title: this.extDefines[i].title, width: 'auto' })
			}

			this.childTabView = []
			let value = ''
			for (let i = 0; i < this.curNode.Child.length; i++) {
				let node = {}
				for (let j = 0; j < this.childTabTitle.length; j++) {
					const tmpNode = this.curNode.Child[i]
					const tabTitle = this.childTabTitle[j]
					console.log('aaaaaa',tmpNode,tabTitle)
					if(tabTitle.field === 'CTime'){
						console.log('CTime')
						node[tabTitle.field] = formatTime2View(tmpNode.CTime)
						continue
					}
					if (j < fixedSize) {
						value = tmpNode[tabTitle.field]
						if (value === undefined) {
							value = '--'
						} else if (tabTitle.field === 'Status') {
							if (value === '1') {
								value = '是'
							} else {
								value = '否'
							}
						}
						node[tabTitle.field] = value
						continue
					}

					if (tabTitle.field === 'ItemType') {
						if (tmpNode.ItemType) {
							value = tmpNode.ItemType
						} else {
							value = '--'
						}
						node[tabTitle.field] = value

					}

					if (j >= beginExtIndex) {
						// 扩展字段
						if (!tmpNode.extends) {
							node[tabTitle.field] = '--'
							continue
						}

						for (let m = 0; m < tmpNode.extends.length; m++) {
							if (tmpNode.extends[m].fieldName === tabTitle.field) {
								value = tmpNode.extends[m].value
								if (value === undefined) {
									value = '--'
								}
								break
							}
						}
					}
					node[tabTitle.field] = value
				}
				this.childTabView.push(node)
			}
		},
		onSelected(node) {
			this.status = 'view'
			this.parentNode = null
			this.curNode = node
			this.genChildTabView()
		},
		onUpdateNode(node) {
			this.status = 'edit'
			this.parentNode = null
			this.curNode = node
			this.genChildTabView()
		},
		onAddNode(node) {
			this.status = 'edit'
			this.parentNode = node
			this.curNode = {
				ParentCode: this.parentNode.ItemCode,
				TreeType: this.parentNode.TreeType,
				Level: String(Number(this.parentNode.Level) + 1),
				ItemType: '',
				Status: '1'
			}

			this.childTabTitle = null
		},
		onDelNode(node) {
			if (node.Child && node.Child.length > 0) {
				this.$message({ message: '该节点还有子节点，请先删除所有子节点', type: 'error', duration: BASE_API.MSG_SHOW_TIME })
				return
			}
			this.status = 'del'
			this.parentNode = null
			this.curNode = node
			this.isDelDialog = true
			this.childTabTitle = null
		},
		async submitDelNode() {
			console.log('[Debug][DelNode]node: ', this.curNode)
			this.isDelDialog = false
			const params = {}
			params.ItemCode = this.curNode.ItemCode
			params.GroupID = this.groupID
			console.log('submitDelNode params',params)
			let res = await httpReqeust.SyncPost('delTreeData', params)
			console.log('res: ' + res)
			if (res.success === true) {
				this.$message({ message: '删除成功', type: 'sucess', duration: BASE_API.MSG_SHOW_TIME })
				this.$refs.Tree.delNode(this.curNode)
			} else {
				this.$message({ message: '删除失败', type: 'error', duration: BASE_API.MSG_SHOW_TIME })
			}
		},

	}
}
</script>
<style scoped>
.mix-tree-list {
	cursor: pointer;
	display: flex;
	flex-direction: column;
	padding-left: 30px;
}
.back {
	background: rgb(204, 204, 204);
}
.mix-tree-item {
	display: flex;
	align-items: center;
	font-size: 16px;
	color: #333;
	height: 0;
	opacity: 0;
	transition: 0.2s;
	position: relative;
}

.mix-tree-item.border {
	border-bottom: 1px solid #eee;
}
.mix-tree-item.show {
	height: 50px;
	opacity: 1;
}
.mix-tree-icon {
	/* width: 26px;
  height: 26px; */
	margin-right: 8px;
	opacity: 0.9;
}

.mix-tree-item.showchild:before {
	transform: rotate(90deg);
}
.mix-tree-item.last:before {
	opacity: 0;
}
.title {
	max-width: 100%;
	margin-right: 40px;
}
.main {
	height: 100%;
	display: flex;
	justify-content: space-between;
	/* 设置超出滚动 */
	overflow-x: auto;
}
.list {
	margin: 15px;
	margin-left: 0;
}
:deep(.el-collapse-item__wrap) {
	overflow: auto !important;
}
.dialog-footer {
	margin-top: 20px;
}
</style>
<style>
.NodeDelete .el-dialog__title {
	color: #4baaf4;
	padding-left: 5px;
	border-left: 5px solid #4baaf4;
	font-size: 22px;
}
</style>
